import { _decorator, Color, Component, Label, Node, Size, Sprite, SpriteFrame, UITransform, v3 } from 'cc';
import { UIManager } from '../common/UIManager';
import { PrefabEnum } from '../common/PrefabEnum';
import { BuildingDetail } from './BuildingDetail';
import { VillageController } from './VillageController';
import { Space } from './Space';
import VillageApi from '../api/VillageApi';
import { UserInfo } from '../common/UserInfo';
import { Building, EventOper } from '../entity/Buildings';
import { BuildingBtnCheck } from './BuildingBtnCheck';
import { BuildingLocalApi } from './BuildingLocalApi';
import { BuildingList } from './BuildingList';
import ResManager from '../common/ResManager';
import { BuildingUpGrade } from './BuildingUpGrade';
import { EventManager } from '../event/EventManager';

const { ccclass, property } = _decorator;

@ccclass('BuildingItem')
export class BuildingItem extends Component {
    @property(Sprite)
    public cover: Sprite;
    @property(Label)
    public buildName: Label;
    @property(Label)
    level:Label
    @property(Sprite)
    headImg: Sprite
    

    /** 建筑物的数据 Building 对象*/
    private data: Building;

    /**建造按钮是否可用 */
    private buildUse: boolean = false
    /**加速按钮是否可用 */
    private speedUpUse: boolean = false
    /**升级按钮是否可用 */
    private upGradeUse: boolean = false
    /**拆除按钮是否可用 */
    private removeUse: boolean = false

    start() {
        this.node.on(Node.EventType.TOUCH_END, this.onClick, this)
       
    }

    async setData(item:Building){
       
        this.data = item
        this.buildName.string = item.name
        this.headImg.spriteFrame = await item.getImg()
        if(item.grade){
            this.level.string = '等级' + item.grade
        } else {
            this.level.node.parent.active = false
        }

        

        Building.setCoverSize(this.cover.node, this.headImg) 
    }

    checkIsCanBuild(){
        let needLevel = this.data.needLevel
        for (let item of needLevel) {
            if (item.isLack) {
                this.headImg.grayscale = true
            }
        }
    }

  

    /**设置工人的数据 */
    async setWorker(item: Building) {
        this.data = item

        this.buildName.string = item.name
       
        if (item.name == '建筑工人') {
            let sf = await ResManager.instance.loadAssetByUrl<SpriteFrame>('uicommon/worker/spriteFrame')
            this.headImg.spriteFrame = sf
        } else {
            let sf = await ResManager.instance.loadAssetByUrl<SpriteFrame>('uicommon/remover/spriteFrame')
            this.headImg.spriteFrame = sf
        }

    }
    /**设置新建的建筑物的数据 */
    async setBuild(item: Building) {

        // 先隐藏所有按钮
      
        this.data = item

        this.buildName.string = item.name


        let needLevel = item.needLevel
        let lackLevel = needLevel.filter(obj => obj.isLack).map(obj => {
            return `${obj.name}${obj.level}级`
        })
        if (lackLevel.length == 0) {
            let pos = this.buildName.node.position
            this.buildName.node.setPosition(v3(pos.x, 0, pos.z))


        } else {
        
        }

        this.headImg.spriteFrame = await item.getImg()


        // this.buildUse = BuildingBtnCheck.checkBuildBtn(this.build, this.data, true)
    }

    /**设置我的建筑物的数据 */
    async setMyBuilding(item: Building) {
       
        this.data = item

      
        // 判断是否满级
        if (!item.isMaxLevel) {
           
        }
        // 正在升级中 或者 正在拆除中的 不能操作
        if (item.isBuilding || item.isRemoving) {
         
        }


        this.buildName.string = item.name

       

        this.headImg.spriteFrame = await item.getImg()
        // this.upGradeUse = BuildingBtnCheck.checkUpGrdeBtn(this.upGrade, item, true)
        // this.removeUse = BuildingBtnCheck.chekcRemoveBtn(this.remove, item, true)
    }

    async setMyRes(item: Building) {
        this.data = item
        this.buildName.string = item.name
        this.headImg.spriteFrame = await item.getImg()
        // this.upGradeUse = BuildingBtnCheck.checkUpGrdeBtn(this.upGrade, item, true)
    }



    async onClick() {
        console.log(this.data)
        if(this.data.id == 0){
            return
        }
        if (this.data.id < 5) {
            // 小于5，表示是资源田
            let ui = await UIManager.instance.openUI(PrefabEnum.BuildingUpGrade)
            ui.getComponent(BuildingUpGrade).setData(this.data)
            return
        }
        if (this.data.gid == null) {
            // 建造页面
            let ui = await UIManager.instance.openUI(PrefabEnum.BuildingDetail)
            ui.getComponent(BuildingDetail).setData(this.data)
        } else {
            // 升级页面
            let ui = await UIManager.instance.openUI(PrefabEnum.BuildingUpGrade)
            ui.getComponent(BuildingUpGrade).setData(this.data)
        }



    }
    // 点击建造按钮
    async onBuild() {

        if (!this.buildUse) {
            return
        }
        
        if(this.data.id == 31 ||this.data.id == 32 || this.data.id == 33){
          
            EventManager.instance.emit(EventManager.EventType.BuildWall, 40)
            UIManager.instance.closeUI(PrefabEnum.BuildingList)
            return
        }

        let space: Space;
        if (VillageController.instance.curClickSpace) {
            space = VillageController.instance.curClickSpace.getComponent(Space)
            space.buildBuilding(this.data.id)
        } else {
            VillageController.instance.curBuilding = this.data
            VillageController.instance.openSpaceTip()
        }





        // 关闭UI 
        UIManager.instance.closeUI(PrefabEnum.BuildingList)
    }

    async onCancel() {
        await UIManager.instance.showLoading()
        let res = await VillageApi.eventOper({
            ac: EventOper.CANCEL,
            eid: this.data.getBuildingEvent().eHandle
        })
        UIManager.instance.closeLoading()
        console.log(`取消，事件句柄${this.data.getBuildingEvent().eHandle}:`, res)
        // BuildingLocalApi.cancel(this.data)
        UserInfo.instance.refreshVillageDetail()

        BuildingList.instance.refreshView()

        // let building = new Building()
        // building.id = 0
        // if (this.data.isBuilding) {
        //     building.name = '建筑工人'
        // }
        // if (this.data.isRemoving) {
        //     building.name = '拆除工人'
        // }
        // building.desc = '空闲中'


        //   //更新本地数据
        //   BuildingLocalApi.cancel(this.data)
        //   this.setWorker(building)
    }

    async onSpeedUp() {
        if (!this.speedUpUse) {
            return
        }

        let param = {
            ac: 0,
            eid: this.data.getBuildingEvent().eHandle
        }
        if (this.data.isBuilding) {
            param.ac = EventOper.SPEED_BUILD
        }
        if (this.data.isRemoving) {
            param.ac = EventOper.SPEED_REMOVE
        }
        await UIManager.instance.showLoading()
        let res = await VillageApi.eventOper(param)
        UIManager.instance.closeLoading()
        console.log(`速拆与速建ac =${param.ac} ,del =${param.eid} `, res)
        //更新本地数据
        // BuildingLocalApi.speed(this.data)
        UserInfo.instance.refreshVillageDetail()


        let building = new Building()
        building.id = 0
        if (this.data.isBuilding) {
            building.name = '建筑工人'
        }
        if (this.data.isRemoving) {
            building.name = '拆除工人'
        }
        building.desc = '空闲中'
        this.setWorker(building)


    }

    async onUpGrade() {
        if (!this.upGradeUse) {
            return
        }

        if(this.data.uid == 40){

            EventManager.instance.emit(EventManager.EventType.BuildWall, 40)
            UIManager.instance.closeUI(PrefabEnum.BuildingList)
            return
        }

        await UIManager.instance.showLoading()
        let res = await VillageApi.buildingOper({
            gid: this.data.id,
            uid: this.data.uid
        })
        console.log(`建造gid=${this.data.id}, uid=${this.data.uid}`, res)
        await UserInfo.instance.refreshVillageDetail()
        UIManager.instance.closeLoading()
        // 关闭UI
        UIManager.instance.closeUI(PrefabEnum.BuildingList)

        VillageController.instance.moveCameraToSpace(this.data.uid)
    }

    async onRemove() {
        if (!this.removeUse) {
            return
        }

        if(this.data.uid == 40){

            EventManager.instance.emit(EventManager.EventType.RemoveWall, 40)
            UIManager.instance.closeUI(PrefabEnum.BuildingList)
            return
        }

        await UIManager.instance.showLoading()
        let res = await VillageApi.destroyBuilding(this.data.uid)
        console.log(`拆除${this.data.uid}:`, res)
        UserInfo.instance.refreshVillageDetail()
        UIManager.instance.closeLoading()
        // 关闭UI
        UIManager.instance.closeUI(PrefabEnum.BuildingList)

        VillageController.instance.moveCameraToSpace(this.data.uid)
    }
}


